package com.example.javapracticaltraining.entity;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

/**
 * @author night
 * @date 2025/06/30
 *
 */
public record R<T>(int code, T data, String msg) {

	public static <T> R<T> error(String msg) {
		return new R<>(500, null, msg);
	}

	public static <T> R<T> success(T data) {
		return new R<>(200,data,"请求成功");
	}
	public static <T> R<T> success() {
		return success(null);
	}

	public static <T> R<T> noPermission() {
		return new R<>(401,null,"权限不足，拒绝访问");
	}

	public static  <T> R<T> unauthorized(String msg) {
		return failure(401, msg);
	}

	public static  <T> R<T> forbidden(String msg) {
		return failure(403, msg);
	}

	public static <T> R<T> failure(int code, String msg) {
		return new R<>(code,null,msg);
	}

	public String asJsonString() {
		return JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls);
	}
}